<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Auth extends Controller
{


    public function action_index()
    {
        $this->response->body('Index');
    }

    public function action_login()
    {
        $post = Validation::factory($_POST);
        $post->rule('user', 'not_empty');
        $post->rule('passwd', 'not_empty');

        if ($post->check())
        {
            if (Auth::instance()->login($_POST['user'], $_POST['passwd']))
            {
                echo json_encode(array('response' => 1));
            }
            else
            {
                echo json_encode(array('response' => 0));
            }
        }
        else
        {
            echo json_encode(array('response' => 0));
        }
    }

    public function action_logout()
    {
        Auth::instance()->logout();
        $this->request->redirect('/');
    }

    public function action_register()
    {
		if ($_POST["recaptcha_response_field"]) 
		{
			$resp = recaptcha_check_answer (
				'6Lek0s0SAAAAANfQ8ocYdBw2FlykvS1WQM1VibUj',
				$_SERVER["REMOTE_ADDR"],
				$_POST["recaptcha_challenge_field"],
				$_POST["recaptcha_response_field"]);

			if ($resp->is_valid) 
			{
               
				$post = Validation::factory($_POST);
				$post->rule('name', 'not_empty');
				$post->rule('email', 'not_empty');
				$post->rule('passwd', 'not_empty');
				$post->rule('passwd2', 'not_empty');
				$post->rule('email', 'email');
				$post->rule('passwd', 'matches', array(':validation', 'passwd', 'passwd2'));
				$post->rule('race_id','not_empty');
				$post->rule('color', 'not_empty');
				$post->rule('name','min_length', array(':value',4));
				$post->rule('name','max_length', array(':value',12));
				$post->rule('name','regex', array(':value','#[a-z][a-z0-9]{3,11}$#i'));
				$post->rule('passwd','min_length',array(':value',6));
				$post->rule('passwd','max_length',array(':value',40));
				$post->rule('passwd','alpha_dash',array(':value',TRUE));
				if ($post->check())
				{
					$user = ORM::factory('user');
					$user->values(array(
						'username' => $_POST['name'],
						'password' => $_POST['passwd'],
						'password_confirm' => $_POST['passwd2'],
						'email' => $_POST['email'],));

					if (ORM::factory('user')->unique_key_exists($_POST['name']))
					{
						echo json_encode(array('status' => 0, 'message' => 'Podana nazwa użytkownika jest zajęta!'));
					}
					elseif (ORM::factory('user')->unique_key_exists($_POST['email']))
					{
						echo json_encode(array('status' => 0, 'message' => 'Podany e-mail jest już zajęty!'));
					}
					elseif (ORM::factory('race')->unique('id',$_POST['race_id'])) // chyba powinno byc bez wykrzyknika
					{
						echo json_encode(array('status' => 0, 'message' => 'Nie ma takiej rasy!'));
					}
					else
					{
						$user->save();
						
						$player = ORM::factory('player');
						$player->user_id = $user->id;
						
						$colors = array('red' => 'czerwony', 'yellow' => 'żółty', 'blue' => 'niebieski');
						$player->color = $colors[$_POST['color']];
						$player->race_id = intval($_POST['race_id']);
						$player->ru = 10000;
						$player->save();
						
						$verify = ORM::factory('code');
						$verify->user_id = $user->id;
						$key = md5(microtime(true).$user->id);
						$verify->key = $key;
						$verify->save();
						
						$email = Email::factory()
						->subject('Aktywacja konta w grze Lokah')
						->to($_POST['email'])
						->from('no-reply@fifi209.pl', 'Fifi209');
					
						$email->message('Witaj w Lokah, aby potwierdzić kliknij w link <a href="http://'.$_SERVER['SERVER_NAME'].'/auth/verify/'.$key.'">Aktywuj</a>', 'text/html');
						$email->send();

						echo json_encode(array('status' => 1, 'message' => 'Zarejestowano!'));
					}
				}
				else
				{
                                    $errors = $post->errors('auth/register',0);
                                    $keys = array_keys($errors);
                                    echo json_encode(array('status' => '0', 'message' => $errors[$keys[0]]));
                                    /*
					$errors = $post->errors();
					if(!empty($errors['email']))
						echo json_encode(array('status' => 0, 'message' => 'Podaj prawidłowy adres email!'));
					else
					   echo json_encode(array('status' => 0, 'message' => var_dump($errors)));
                                     * */
				}
			}
			else
			{
				echo json_encode(array('status' => 0, 'message' => 'Błędny kod zabezpieczający!'));
			}
		}

    }
	
	public function action_verify() 
	{
		$key = $this->request->param('key');
		
		$verify = ORM::factory('code')->where('key', '=', $key)->find();
		$id = $verify->user_id;
		
		if ($id > 0) 
		{
			$user = ORM::factory('user')->where('id', '=', $id)->find();
			$role = ORM::factory('role', 1);
			
			if ($user->has('roles', $role)) 
			{
				$this->response->body('To konto zostało już zweryfikowane');
			}
			else
			{
				$user->add('roles', $role);
				$user->save();
				$this->response->body('Konto zweryfikowane');
			}
		}
		else
		{
			$this->response->body('Błędny kod');
		}
	}

}

// End Welcome
